//
//  LoadBundleFile.swift
//  DataParsing
//
//  Created by 李煜 on 2024/9/25.
//

import Foundation

// MARK: -  查找项目本地资源方式有两种

enum LoadMainBundleFileError: Error {
	case fileNotFound
	case dataLoadingFailed(Error)
	case decodingFailed(Error)
	case unknownError
}

/// 加载项目资源
/// - Parameters:
///   - source: 资源名称
///   - extension: 资源后缀
///   - type: 模型类
/// - Returns: 可选模型对象
func aloadMainBundleFile<T: Decodable>(_ source: String?, _ ext: String?, _ type: T.Type) -> Result<T, LoadMainBundleFileError> {
		// 尝试获取文件的 URL
	guard let url = Bundle.main.url(forResource: source, withExtension: ext) else {
		return .failure(.fileNotFound) // 文件未找到
	}
	
	do {
			// 尝试加载数据
		let data = try Data(contentsOf: url)
			// 尝试解码数据
		let obj = try JSONDecoder().decode(type, from: data)
		return .success(obj) // 返回成功的结果// 可能是一个有效的 T 或者 nil
	} catch let error as CocoaError {
			// 处理 CocoaError
		switch error.code {
			case .fileReadNoPermission:
				return .failure(.dataLoadingFailed(error))
			case .fileReadCorruptFile:
				return .failure(.dataLoadingFailed(error))
			case .fileReadUnknown:
				return .failure(.dataLoadingFailed(error))
			default:
				return .failure(.unknownError)
		}
	} catch {
			// 捕获其他类型的错误（如解码错误）
		return .failure(.decodingFailed(error))
	}
}

func bloadMainBundleFile<T>(_ source: String?, _ ext: String?, _ type: T.Type) throws -> T? where T: Decodable {
	guard let url = Bundle.main.url(forResource: source, withExtension: ext),
				let data = try? Data(contentsOf: url),
				let obj = try? JSONDecoder().decode(type, from: data) else { return nil }
	return obj
}
